package cn.chengpengper.netdisk.service.impl;

import cn.chengpengper.netdisk.config.AccountConfig;
import cn.chengpengper.netdisk.controller.request.AccountRegisterReq;
import cn.chengpengper.netdisk.enums.AccountRoleEnum;
import cn.chengpengper.netdisk.enums.BizCodeEnum;
import cn.chengpengper.netdisk.exception.BizException;
import cn.chengpengper.netdisk.mapper.AccountMapper;
import cn.chengpengper.netdisk.model.AccountDO;
import cn.chengpengper.netdisk.service.AccountService;
import cn.chengpengper.netdisk.util.SpringBeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class AccountServiceImpl implements AccountService {

    private final AccountMapper accountMapper;

    @Override
    public void register(AccountRegisterReq req) {
        LambdaQueryWrapper<AccountDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccountDO::getPhone, req.getPhone());
        List<AccountDO> list = accountMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            throw new BizException(BizCodeEnum.ACCOUNT_REPEAT);
        }

        AccountDO account = SpringBeanUtil.copyProperties(req, AccountDO.class);
        // 加密密码
        String pwd = DigestUtils.md5DigestAsHex((AccountConfig.ACCOUNT_PWD_SALT + req.getPassword()).getBytes(StandardCharsets.UTF_8));
        account.setPassword(pwd);
        account.setRole(AccountRoleEnum.COMMON.name());
        accountMapper.insert(account);
    }
}
